package real.unknown.imitate.collection;


public class MyHashMap<K, V> {

    private Node<K, V>[] table;
    private int capacity;
    private double theshold;

    public MyHashMap() {
        new MyHashMap(16);
    }

    public MyHashMap(int capacity) {
        this.capacity = capacity;
        table = new Node[capacity];
        this.theshold = 0.75;
    }

     class Node<K, V> {
        K key;
        V val;
        Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }

    }

    public int hash(K key) {
        int h;
        return key == null ? 0 : (h = key.hashCode()) ^ (h >> 16);
    }

    public boolean put(K key, V val) {
        int hashcode = hash(key);
        int idx = hashcode ^ (capacity - 1);
        Node<K, V> node = new Node<>(key, val);
        if (table[idx] == null) table[idx] = node;
        else {
            Node<K, V> cur = table[idx];
            if (key == null) {
                while (cur.next !=null && cur.key != null) {
                    cur = cur.next;
                }
            } else {
                while (cur.next != null && !cur.key.equals(key)) {
                    cur = cur.next;
                }
            }

            if (cur.key == null && key == null) {
                cur.val = val; //灏嗙┖鍊艰妭鐐硅鐩�
            } else if (cur.key.equals(key)) {
                cur.val = val;
            } else {
                cur.next = node;
            }
            
        }
        return true;
    }

    public V get(K key) {
        int idx = hash(key) & (capacity - 1);
        if (table[idx] == null) return null;
        else {
            Node<K, V> cur = table[idx];
            if (key == null) {
                while (cur != null && cur.key != null) cur = cur.next;
                if (cur == null) return null;
                else return cur.val;
            } else {
                while (cur != null && !key.equals(cur.key)) cur = cur.next;
                return cur == null ? null : cur.val;
            }
        }
    }
}
